/*
 * @Author: Ben Fang
 * @Date: 2022-06-02 08:14:00
 * @LastEditors: Ben Fang
 * @LastEditTime: 2022-06-02 15:34:58
 */
const puppeteer = require("puppeteer");
const express = require("express");
const bodyParser = require("body-parser");
const gm = require("./image.js");

const app = express();
app.use(bodyParser.json());
app.use(
  bodyParser.urlencoded({
    extended: true,
  })
);

// 设置跨域
const allowCrossDomain = (req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*"); //自定义中间件，设置跨域需要的响应头。
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, OPTIONS, PUT, DELETE"
  ); //允许任何方法
  res.setHeader(
    "Access-Control-Allow-Headers",
    "X-Requested-With,content-type,X-Session-Token"
  ); //允许任何类型
  next();
};

app.use(allowCrossDomain);

// 创建接口
app.post("/screenshot", (req, res) => {
  const { paths, width, height, uploadPath } = req.body;
  if (typeof paths === "object") {
    const screenshot = async () => {
      const browser = await puppeteer.launch({
        args: ["--no-sandbox"],
        ignoreHTTPSErrors: true,
        headless: true,
      });
      for (let index = 0; index < paths.length; index++) {
        const page = await browser.newPage();
        await page.setViewport({
          width: width || 1920,
          height: height || 1080,
          deviceScaleFactor: 1,
        });
        await page.setDefaultNavigationTimeout(0);
        await page.goto(paths[index], { waitUntil: "networkidle0" });
        await page.screenshot({
          path: `./images/push${index}.png`,
          fullPage: true,
        });
      }

      await browser.close();
    };
    screenshot().then(() => {
      gm.convertImage(uploadPath);
      return res.send({ code: 200, msg: "success" });
    });
  } else {
    return res.send({ code: 500, msg: "path参数不正确或为空" });
  }
});

const port = 9000;
const host = "127.0.0.1";
app.listen(port, host, () => {
  console.log(`Server is running on http://localhost:9000`);
});
